// section template
<template>
  <div>
    <el-dialog
      :before-close="handleClose"
      :title="status === 1 ? '新增版本' : '编辑版本'"
      :visible.sync="dialogVisible"
      width="60%"
      @close="handleCloseDialog"
      @opened="initWangEditor"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="发版类型" prop="app_type">
            <el-radio-group v-model="form.app_type" @change="appTypeChang">
              <el-radio :label="1">Android</el-radio>
              <el-radio :label="2">iOS</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input v-model="form.version"></el-input>
          </el-form-item>
          <el-form-item label="更新文案">
            <div style="height:350px">
              <div id="wang_editor" ref="wang_editor"></div>
            </div>
          </el-form-item>
          <el-form-item label="虚拟器下载" prop="simulator_url">
            <el-input v-model="form.simulator_url"></el-input>
          </el-form-item>
          <!--          <el-form-item-->
          <!--            v-if="form.app_type === 1"-->
          <!--            label="安装包"-->
          <!--            prop="install_type"-->
          <!--          >-->
          <!--            <el-radio-group v-model="form.install_type">-->
          <!--              <el-radio :label="1">上传安装包</el-radio>-->
          <!--              <el-radio :label="2">填写下载链接</el-radio>-->
          <!--            </el-radio-group>-->
          <!--          </el-form-item>-->
          <!--          v-if="form.app_type === 2"-->
          <el-form-item
            label="安装地址"
            prop="install_url"
          >
            <el-input v-model="form.install_url"></el-input>
          </el-form-item>
          <!--   :before-upload="beforeUpload"          -->
          <!--          <el-upload-->
          <!--            v-if="form.install_type === 1 && form.app_type === 1"-->
          <!--            :action="uploadUrl"-->
          <!--            :before-remove="beforeRemove"-->
          <!--            :file-list="fileList"-->
          <!--            :headers="{token}"-->
          <!--            :http-request="customizeUpload"-->
          <!--            :limit="1"-->
          <!--            :on-exceed="handleExceed"-->
          <!--            :on-preview="handlePreview"-->
          <!--            :on-remove="handleRemove"-->
          <!--            :on-success="handleSuccess"-->
          <!--            class="upload-demo ml-14 mb-5"-->
          <!--            name="install_url"-->
          <!--          >-->
          <!--            <el-button size="small" type="primary">点击上传</el-button>-->
          <!--          </el-upload>-->
          <!--          <div v-for="item in fileList" :key="item.uid">{{ item.name }}</div>-->
          <!--          v-if="form.install_type === 2"-->
          <el-form-item
            label="安装地址"
            prop="install_url"
          >
            <el-input v-model="form.install_url"></el-input>
          </el-form-item>
          <el-form-item label="更新方式" prop="update_type">
            <el-radio-group
              v-model="form.update_type"
              @change="updateTypeChange"
            >
              <el-radio :label="1">强制更新</el-radio>
              <el-radio :label="2">自主更新</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.update_type === 2"
            label="弹窗方式"
            prop="pop_type"
          >
            <el-radio-group v-model="form.pop_type">
              <el-radio :label="1">每次启动应用弹出</el-radio>
              <el-radio :label="2">每天仅第一次启动弹出一次</el-radio>
              <el-radio :label="3">每周仅第一次启动弹出一次</el-radio>
              <el-radio :label="4">本次更新仅第一次启动弹出一次</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="华为强更"
            prop="hw_uptype"
          >
            <el-radio-group v-model="form.hw_uptype">
              <el-radio :label="0">不强更</el-radio>
              <el-radio :label="1">强更</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="版本状态" prop="version_status">
            <el-radio-group v-model="form.version_status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="二维码" prop="img_url">
            <el-upload
              :http-request="customizeUpload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
            >
              <img v-if="form.img_url" :src="form.img_url" class="avatar"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeClick">取 消</el-button>
        <el-button type="primary" @click="submitClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import { addAppManagement, editAppManage } from '@/api/config/listVersion'
import wangEditor from 'wangeditor'
import { getToken } from '@/utils/auth'

const token = getToken()

export default {
  name: 'modalConfig',
  // section props
  props: {
    // 状态, 当为 1 时, 新增版本, 当为 2 时， 编辑版本
    status: {
      type: Number,
      default() {
        return 1
      }
    },
    detail: {
      type: Object,
      default() {
        return {}
      }
    },
    dialogVisible: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      token,
      wangEdit: null,

      uploadUrl:
        process.env.BASE_API +
        'system-set/app-version/management/apk/uploadApk',
      form: {
        // app类型
        app_type: null,
        // 安卓应用类型 1 回声 2回声
        android_application_type: 1,
        // 版本号
        version: null,
        // 安装方式 1 上传安装包 2 填写下载链接 3 iOS安装地址
        install_type: null,
        // 安装地址 注：如果选择安装方式为1 该传过来的值不为字符串 为文件类型
        install_url: null,
        // 更新方式 1 强制更新 2自主更新
        update_type: null,
        // 弹窗方式 1 每次启动应用弹窗 2每天仅第一次启动弹出一次 3每周仅第一次启动弹出一次 4本次更新仅第一次启动弹出一次
        pop_type: null,
        // 版本状态 1 启用 2禁用
        version_status: null,
        // 更新文案
        update_content: null,
        // 华为是否强更
        hw_uptype: null,
        img_url: undefined,
      },
      rules: {
        app_type: [
          { required: true, message: '请选择发版类型', trigger: 'blur' }
        ],
        android_application_type: [
          { required: true, message: '请选择选择应用', trigger: 'blur' }
        ],
        version: [{ required: true, message: '请选择版本号', trigger: 'blur' }],
        install_type: [
          { required: true, message: '请选择安装包', trigger: 'blur' }
        ],
        install_url: [
          { required: true, message: '请输入安装地址', trigger: 'blur' }
        ],
        update_type: [
          { required: true, message: '请选择更新方式', trigger: 'blur' }
        ],
        hw_uptype: [
          { required: true, message: '请选华为是否强更', trigger: 'blur' }
        ],
        pop_type: [
          { required: true, message: '请选择弹窗方式', trigger: 'blur' }
        ],
        version_status: [
          { required: true, message: '请选择版本状态', trigger: 'blur' }
        ],
        img_url: [{required: true, message: '请上传图片', trigger: 'blur'}],
      },
      fileList: [],
      file: {}
    }
  },
  methods: {
    initWangEditor() {
      this.wangEdit = new wangEditor(this.$refs['wang_editor'])
      this.wangEdit.config.height = 250
      // this.wangEdit.config.uploadImgServer = IMG_UPLOAD_URL
      this.wangEdit.config.uploadFileName = 'file'
      this.wangEdit.config.uploadImgHooks = {
        customInsert: (insertImgFn, { data }) => insertImgFn(data.url)
      }
      this.wangEdit.config.onchange = newHtml => (this.editShowWord = newHtml)
      this.wangEdit.create()

      if (this.status === 2) {
        this.wangEdit.txt.html(this.detail.update_content)
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.closeClick()
        })
        .catch(_ => {
        })
    },
    handleRemove(file, fileList) {
      this.form.install_url = null
      this.fileList.pop()
    },
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`)
    },
    handleSuccess(detail) {
      // console.log(detail)
      // let { data } = detail
      // this.form.install_url = data.url
      this.form.install_url = this.ossLastImgUrl
    },
    beforeUpload(file) {
      this.file = file
      this.fileList.push(file)
    },
    /**
     * appTypeChang
     * @desc 当发版类型发生改变时 清空选择应用中的数据
     * @param val
     */
    appTypeChang(val) {
      this.form.android_application_type = null
      this.form.install_type = null
    },
    /**
     * updateTypeChange
     * @desc 当更新方式发生改变时,  弹窗方式数据清空
     * @param val
     */
    updateTypeChange(val) {
      this.form.pop_type = null
    },
    closeClick() {
      for (const argumentsKey in this.form) {
        this.form[argumentsKey] = null
      }
      this.$emit('update:dialogVisible', false)
      this.$emit('update:status', 1)
    },
    /**
     * submitClick
     * @desc 点击确认按钮
     */
    submitClick() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          // 处理数据

          this.form.update_content = this.wangEdit.txt.html().replaceAll('&nbsp;', ' ')

          if (this.form.install_type === 1 && this.form.app_type === 1 && this.form.install_url === null) {
            this.$message.info('安装包还未上传成功')
            return
          }

          // 当状态为 1 时, 为新建版本
          let detail = null
          let form = {}
          for (const formKey in this.form) {
            // 排除为 null 的变量
            if (
              !(
                !this.form[formKey] &&
                typeof this.form[formKey] != 'undefined' &&
                this.form[formKey] !== 0
              )
            ) {
              form[formKey] = this.form[formKey]
            }
          }
          //
          if (this.status === 1) {
            const formData = new FormData()
            Object.keys(form).forEach(key => {
              formData.append(key, form[key])
            })
            detail = await addAppManagement(formData)
          } else {
            detail = await editAppManage(this.detail.id, form)
          }
          if (detail.data) {
            this.$message.success(this.status === 1 ? '新增成功' : '编辑成功')
            this.$emit('updateTable')
            this.$emit('update:dialogVisible', false)
            this.$emit('update:status', 1)
            for (const formKey in this.form) {
              this.form[formKey] = null
            }
          }
        } else {
          return false
        }
      })
    },
    handleCloseDialog() {
      this.$refs['form'].resetFields()
      this.$refs['wang_editor'].innerHTML = ''
      this.wangEdit.destroy()
      this.wangEdit = null
      // this.editShowPirtureList = []
      // this.editShowWord = ''
    },

    handleAvatarSuccess(res, file) {
      this.form.img_url = this.ossLastImgUrl
    },
    beforeAvatarUpload2(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      this.form.img_url = file
      console.log(file)
      // return isJPG && isLt2M;
    },
  },
  watch: {
    status(newVal, oldVal) {
      if (newVal === 2) {
        this.fileList = []
        if (this.detail.install_url) {
          this.fileList.push({ name: '文件', url: this.detail.install_url })
        }
        this.form = Object.assign(this.form, this.detail)
      }
    }
  },
  beforeDestroy() {
    this.wangEdit = null
  }
}
</script>

// section style
<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}

</style>
